package com.softserveinc.network;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class BitmapManager {

	private static final String ANDROID_DATA_COM_SOFTSERVEINC_CACHE = "/Android/data/com.softserveinc/cache/";
	private static final String TAG = BitmapManager.class.getSimpleName();

	private final Context context;

	public BitmapManager(final Context context) {
		this.context = context;
	}

	public static Uri getUriForImage(final Context context,
			final String fileName) {
		String path;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			path = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ ANDROID_DATA_COM_SOFTSERVEINC_CACHE;

		} else {
			path = context.getCacheDir().getAbsolutePath();
		}

		File file = new File(path, fileName);

		return Uri.fromFile(file);
	}

	public String saveImage(final Bitmap bitmap) {
		if (bitmap == null) {
			return null;
		}

		File myDir;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String path = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + ANDROID_DATA_COM_SOFTSERVEINC_CACHE;

			forceHidding(path);

			myDir = new File(path);
			myDir.mkdirs();

			// Log.i(TAG, path);
		} else {
			// Log.e(TAG, "no sd");

			myDir = context.getCacheDir();
		}

		String fname = "Image-" + bitmap.hashCode() + ".jpg";

		// Log.e(TAG, myDir.getAbsolutePath());

		File file = new File(myDir, fname);

		if (file.exists()) {
			file.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
			Log.d(TAG, "bitmap saved in " + myDir.getAbsolutePath());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "error " + fname);
		}

		return fname;
	}

	private void forceHidding(final String path) {
		File file = new File(path, ".nomedia");

		try {
			file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Bitmap getBitmapForLocalUrl(final String name)
			throws FileNotFoundException {
		InputStream inputStream;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {

			String path = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + ANDROID_DATA_COM_SOFTSERVEINC_CACHE;

			// Log.d(TAG, "if mounted: " + path);
			File myDir = new File(path);
			// Log.d(TAG, "myDir: " + myDir.getAbsolutePath());
			// Log.d(TAG, "fileName: " + name);
			File file = new File(myDir, name);
			// Log.d(TAG, "full path: " + file.getAbsolutePath());

			try {
				inputStream = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				myDir = context.getCacheDir();
				file = new File(myDir, name);
				inputStream = new FileInputStream(file);
			}
		} else {
			Log.e(TAG, context.getCacheDir().getAbsolutePath());
			File myDir = context.getCacheDir();
			File file = new File(myDir, name);
			inputStream = new FileInputStream(file);
		}

		return BitmapFactory.decodeStream(inputStream);
	}

	public static void copyCacheToExternalFolder(final Context context) {
		String path = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + ANDROID_DATA_COM_SOFTSERVEINC_CACHE;

		File cacheDir = context.getCacheDir();
		String[] files = cacheDir.list();

		if (files != null) {

			for (int i = 0; i < files.length; i++) {

				File inFile = new File(cacheDir, files[i]);

				try {
					InputStream inputStream = new FileInputStream(inFile);

					Bitmap image = BitmapFactory.decodeStream(inputStream);

					File myDir = new File(path);
					myDir.mkdirs();

					File file = new File(myDir, files[i]);

					if (file.exists()) {
						file.delete();
					}

					FileOutputStream out = new FileOutputStream(file);
					image.compress(Bitmap.CompressFormat.JPEG, 90, out);
					out.flush();
					out.close();

					inFile.delete();
				} catch (FileNotFoundException e) {

					e.printStackTrace();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
		}
	}

	public Bitmap getBitmapForHttpUrl(final String url) {

		int retry = 0;

		for (;;) {
			try {
				HttpURLConnection connection = (HttpURLConnection) new URL(url)
						.openConnection();
				connection.setRequestProperty("User-agent", "Mozilla/4.0");

				connection.connect();

				InputStream input = connection.getInputStream();

				Bitmap image = BitmapFactory.decodeStream(input);

				return image;
			} catch (Exception e) {
				Log.e(TAG,
						BitmapManager.class.getSimpleName() + " "
								+ e.getMessage());

				retry++;

				if (retry == 5) {
					break;
				}
			}
		}

		return null;
	}
}
